<template>
  <transition name="fade">
    <div
      v-show="visible"
      class="group/tooltip fixed right-6 bottom-24 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-full p-2.5 cursor-pointer shadow-lg hover:shadow-xl transition-all duration-300 z-50 border border-gray-200 dark:border-gray-700"
      @click="scrollToTop"
    >
      <div class="w-8 h-8 flex items-center justify-center">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          class="h-6 w-6 text-primary-500 dark:text-primary-400"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2.5"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <path d="M18 15l-6-6-6 6" />
        </svg>
      </div>
      <!-- Tooltip -->
      <div
        class="absolute bottom-full right-1/2 translate-x-1/2 mb-2 opacity-0 group-hover/tooltip:opacity-100 transition-opacity duration-200 pointer-events-none"
      >
        <div
          class="bg-gray-800 dark:bg-gray-700 text-white text-sm px-3 py-1.5 rounded-lg shadow-md whitespace-nowrap"
        >
          返回顶部
          <div
            class="absolute bottom-0 left-1/2 -translate-x-1/2 translate-y-full w-2 h-2 transform rotate-45 bg-gray-800 dark:bg-gray-700"
          ></div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: "BackToTop",
  data() {
    return {
      visible: false,
      scrollThreshold: 300, // 滚动超过300px时显示按钮
    };
  },
  mounted() {
    window.addEventListener("scroll", this.toggleVisibility);
  },
  beforeUnmount() {
    window.removeEventListener("scroll", this.toggleVisibility);
  },
  methods: {
    toggleVisibility() {
      this.visible = window.pageYOffset > this.scrollThreshold;
    },
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    },
  },
};
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
</style>
